#include "dialog.h"
#include "ui_dialog.h"
#include <QDebug>

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    socket = new QTcpSocket;
    socket->connectToHost("192.168.0.8",8089);
    QByteArray arr="hello world";
    socket->write(arr);
    connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(DealSendMsg()));
    connect(ui->radioButton,SIGNAL(clicked()),this,SLOT(DealLed1Msg()));
    connect(ui->radioButton_2,SIGNAL(clicked()),this,SLOT(DealLed2Msg()));
    connect(ui->radioButton_3,SIGNAL(clicked()),this,SLOT(DealLed3Msg()));
    connect(ui->radioButton_4,SIGNAL(clicked()),this,SLOT(DealJDQMsg()));

    connect(socket,SIGNAL(readyRead()),this,SLOT(DealreqAnswer()));

}
void Dialog::DealSendMsg()

{
    qDebug()<<"etst";
    QByteArray arr="are you ok";
    socket->write(arr);
}

void Dialog::DealLed1Msg()
{
    QByteArray arr ;
    if(led1_flag == 1)
    {
        arr="led1_off";
        led1_flag =0;
    }else
    {
        arr="led1_on";
        led1_flag =1;
    }

    socket->write(arr);
}

void Dialog::DealLed2Msg()
{
    QByteArray arr ;
    if(led2_flag == 1)
    {
        arr="led2_off";
        led2_flag =0;
    }else
    {
        arr="led2_on";
        led2_flag =1;
    }

    socket->write(arr);
}

void Dialog::DealLed3Msg()
{
    QByteArray arr ;
    if(led3_flag == 1)
    {
        arr="led3_off";
        led3_flag =0;
    }else
    {
        arr="led3_on";
        led3_flag =1;
    }

    socket->write(arr);
}

void Dialog::DealJDQMsg()
{
    QByteArray arr ;
    if(JDQ_flag == 1)
    {
        arr="jdq_off";
        JDQ_flag =0;
    }else
    {
        arr="jdq_on";
        JDQ_flag =1;
    }

    socket->write(arr);
}
void Dialog::DealreqAnswer()
{
    QByteArray arr = socket->readAll();


        static QByteArray newjpg;
        static bool start_flag = 0;
        static bool end_flag = 0;
        for(int i = 0; i<arr.size();i++)
        {
            if(arr[i]==0xff && arr[i+1]==0xd8)
            {

                qDebug()<<"start";
                start_flag = 1;
            }

            if(arr[i]==0xff && arr[i+1]==0xd9)
            {

                qDebug()<<"end";
                newjpg +=arr[i];
                newjpg +=arr[i+1];
                start_flag = 0;
                end_flag = 1;
            }
            if(start_flag == 1)
            {
                newjpg +=arr[i];
            }
        }
        QImage image = QImage::fromData(newjpg, "JPG");

//        QPixmap picture;
//        picture.loadFromData(newjpg);
    if(end_flag == 0)
        return;
    ui->label_vedio->setPixmap(QPixmap::fromImage(image));
    newjpg.clear();
    end_flag = 0;


}
Dialog::~Dialog()
{
    delete ui;
}
